<template>
  <el-scrollbar @scroll="scroll" ref="scrollbarRef">
    <slot></slot>
  </el-scrollbar>
</template>
<script setup>
const scrollbarRef = ref(null)

const props = defineProps({})

const autoScroll = ref(true)
let lastScrollTop = 0
let time

const scroll = ({ scrollTop }) => {
  const el = scrollbarRef.value.wrapRef

  if (scrollTop > lastScrollTop) {
    // 检查是否滚动到底部
    if (!autoScroll.value && isScrolledToBottom(el)) openAutoScroll()
  } else if (scrollTop < lastScrollTop) {
    // 向上滚动
    if (autoScroll.value) closeAutoScroll()
  }

  lastScrollTop = scrollTop
}

// 关闭自动滚动
const closeAutoScroll = () => {
  autoScroll.value = false
  clearInterval(time)
}

// 开启自动滚动
const openAutoScroll = () => {
  console.log('openAutoScroll')

  autoScroll.value = true
  scrollToBottom()

  time = setInterval(() => {
    scrollToBottom()
  }, 1000)
}

// 滚动到底部
const scrollToBottom = () => {
  if (!autoScroll.value) return console.log('关闭滚动')
  if (!scrollbarRef.value) return

  scrollbarRef.value.setScrollTop(scrollbarRef.value.wrapRef.scrollHeight)
}

function isScrolledToBottom(element, threshold = 50) {
  return element.scrollHeight - element.scrollTop - element.clientHeight <= threshold
}

defineExpose({
  openAutoScroll,
  closeAutoScroll,
})

onUnmounted(() => {
  clearInterval(time)
})
</script>
<style lang="scss" scoped></style>
